package com.mxpio.erp.plan.service.impl;

import com.mxpioframework.common.util.BeanReflectionUtils;
import com.mxpioframework.common.vo.Result;
import org.springframework.stereotype.Service;

import com.mxpio.erp.common.plan.entity.PurchasePlan;
import com.mxpio.erp.common.plan.service.PurchasePlanService;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class PurchasePlanServiceImpl extends BaseServiceImpl<PurchasePlan> implements PurchasePlanService {

    @Override
    @Transactional
    public Result<PurchasePlan> split(String planNo, BigDecimal splitNum) {
        if (splitNum.compareTo(BigDecimal.ZERO)<=0){
            return Result.error("拆分数量为正整数！");
        }
        PurchasePlan dbPlan = getById(PurchasePlan.class, planNo);
        if (dbPlan==null){
            return Result.error("planNo无效，未能匹配到对应计划数据！");
        }
        BigDecimal quantity = dbPlan.getQuantity();
        if (splitNum.compareTo(quantity)>=0){
            return Result.error("拆分数量只能小于计划数量！");
        }
        quantity = quantity.subtract(splitNum);
        dbPlan.setQuantity(quantity);//修改原计划数量
        update(dbPlan);
        //复制计划
        PurchasePlan copyPlan = new PurchasePlan();
        BeanReflectionUtils.copyProperties(copyPlan,dbPlan);
        copyPlan.setPlanNo(null);
        copyPlan.setQuantity(splitNum);
        save(copyPlan);

        return Result.OK(copyPlan);
    }
}
